package com.ims.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ims.dao.LogPwdErrMapper;
import com.ims.dao.UserLogMapper;
import com.ims.pojo.User;
import com.ims.pojo.LogPwdErr;
import com.ims.pojo.UserLog;
import com.ims.service.LogPwdErrService;
import com.ims.util.DateUtil;
import com.ims.util.LogUtil;
import com.ims.util.RequestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

@Service
public class LogPwdErrServiceImpl extends ServiceImpl<LogPwdErrMapper, LogPwdErr> implements LogPwdErrService {
    @Autowired
    private LogPwdErrService logPwdErrService;

    @Autowired
    private UserLogMapper userLogMapper;

    @Override
    /**
     * 验证用户的登录失败次数  如果失败的次数大于 5，则返回false;否则返回true
     */
    public boolean logErrValid(User user, HttpServletRequest request) {
        String username = user.getUsername();
        LambdaQueryWrapper<LogPwdErr> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(LogPwdErr::getUserName, username);
        LogPwdErr one = logPwdErrService.getOne(lambdaQueryWrapper);

        //判断这个用户的err_num 是否大于5
        if (one != null && one.getErrNum() > 4) {
            // 判定为非法登录，记录用户日志
            UserLog userLog = new UserLog();
            userLog.setUserId(user.getUserId());
            userLog.setUsername(user.getUsername());
            userLog.setOperation(LogUtil.illegalLogin);
            userLog.setEventTime(DateUtil.getFullTime());
            userLog.setIpAddress(RequestUtil.getIpAddress(request));
            userLogMapper.insert(userLog);
            return false;
        } else return true;
    }

    /**
     * 当用户登录失败  会增加登录失败的次数
     *
     * @param user
     */
    public void addErrorNum(User user) {
        String username = user.getUsername();
        LambdaQueryWrapper<LogPwdErr> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(LogPwdErr::getUserName, username);
        LogPwdErr one = logPwdErrService.getOne(lambdaQueryWrapper);
        int errNum = one.getErrNum() + 1;
        LambdaUpdateWrapper<LogPwdErr> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(LogPwdErr::getUserName, username).set(LogPwdErr::getErrNum, errNum);

        Date date = new Date();//获得系统时间.
        SimpleDateFormat sdf = new SimpleDateFormat(" yyyy-MM-dd HH:mm:ss ");
        String nowTime = sdf.format(date);
        try {
            Date time = sdf.parse(nowTime);
            lambdaUpdateWrapper.eq(LogPwdErr::getUserName, username).set(LogPwdErr::getLastDate, time);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        logPwdErrService.update(lambdaUpdateWrapper);
    }

    /**
     * 当用户登录成功，会将 errNum 置零
     *
     * @param user
     */
    @Override
    public void clearErrorNum(User user) {
        String username = user.getUsername();
        LambdaUpdateWrapper<LogPwdErr> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(LogPwdErr::getUserName, username).set(LogPwdErr::getErrNum, 0);
        Date date = new Date();//获得系统时间.
        SimpleDateFormat sdf = new SimpleDateFormat(" yyyy-MM-dd HH:mm:ss ");
        String nowTime = sdf.format(date);
        try {
            Date time = sdf.parse(nowTime);
            lambdaUpdateWrapper.eq(LogPwdErr::getUserName, username).set(LogPwdErr::getLastDate, time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        logPwdErrService.update(lambdaUpdateWrapper);
    }

    /**
     * 当经过30min后,解除登录限制(将err_num置零)
     */
    @Override
    public boolean checkTime(User user) {
        Date date = new Date();//获得系统时间.
        Date date1 = new Date();
        Date date2 = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat(" yyyy-MM-dd HH:mm:ss ");
        String nowTime = sdf.format(date);
        int t = 30 * 60 * 1000;  //30分钟
        try {
            Date time = sdf.parse(nowTime); //得到指定格式的时间
            long dateNow = time.getTime();  //当前系统时间 long类型
            long dateNow_pass = dateNow - t; //当前系统时间 经过t时间后的时间
            date1 = new Date(dateNow_pass); //将经过t时间后的long类型  转为date类型
        } catch (ParseException e) {
            e.printStackTrace();
        }

        String username = user.getUsername();
        LambdaQueryWrapper<LogPwdErr> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(LogPwdErr::getUserName, username);
        LogPwdErr one = logPwdErrService.getOne(lambdaQueryWrapper);

        LocalDateTime lastDate = one.getLastDate(); //从数据库中获取时间
        date2 = Date.from(lastDate.atZone(ZoneId.systemDefault()).toInstant()); //将LocalDateTime类型转为Date
        //compareTo()方法的返回值，date1小于date2返回-1，date1大于date2返回1，相等返回0
        int compareTo = date1.compareTo(date2);
        if (compareTo == 1) { //满足条件  已经超过t时间
            logPwdErrService.clearErrorNum(user);
            return true;
        } else return false;

    }

    /**
     * 添加新用户到 table_user后，将该用户同步添加到log_pwd_err表中
     * @param username
     */
    @Override
    public void add(String username) {
        LogPwdErr logPwdErr = new LogPwdErr();
        logPwdErr.setUserName(username);
        logPwdErrService.save(logPwdErr);
    }

}
